package cn.tedu.medicalpath.inspection.service.impl;

import cn.tedu.medicalpath.base.constant.InspectionStatus;
import cn.tedu.medicalpath.inspection.mapper.InspectionMapper;
import cn.tedu.medicalpath.inspection.mapper.SubInspectionMapper;
import cn.tedu.medicalpath.inspection.pojo.dto.SubInspectionDeleteParam;
import cn.tedu.medicalpath.inspection.pojo.dto.SubInspectionEditParam;
import cn.tedu.medicalpath.inspection.pojo.dto.UnInspectedItemQuery;
import cn.tedu.medicalpath.inspection.pojo.entity.Inspection;
import cn.tedu.medicalpath.inspection.pojo.entity.SubInspection;
import cn.tedu.medicalpath.inspection.pojo.vo.InspectionPersonVO;
import cn.tedu.medicalpath.inspection.pojo.vo.SubInspectionVO;
import cn.tedu.medicalpath.inspection.pojo.vo.UnInspectedItemVO;
import cn.tedu.medicalpath.inspection.service.SubInspectionService;
import cn.tedu.medicalpath.order.mapper.OrderMapper;
import cn.tedu.medicalpath.order.pojo.param.OrderQuery;
import cn.tedu.medicalpath.order.pojo.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubInspectionServiceImpl implements SubInspectionService {
    @Autowired
    private SubInspectionMapper subInspectionMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public List<SubInspectionVO> selectById(Long id) {
        log.debug("开始处理【根据检查单id查询检查项】的请求，参数：{}", id);
        List<SubInspectionVO> subInspectionVOList = subInspectionMapper.selectById(id);
        //根据查出来的检查项目id查询检查项目名称
        subInspectionVOList.forEach(subInspectionVO -> {
            String name = subInspectionMapper.selectNameById(subInspectionVO.getInspectionItemId());
            subInspectionVO.setName(name);
        });
        return subInspectionVOList;
    }
    @Override
    public void edit(SubInspectionEditParam subInspectionEditParam) {
        log.debug("开始处理【编辑检查项】的请求，参数：{}", subInspectionEditParam);
        SubInspection subInspection = new SubInspection();
        BeanUtils.copyProperties(subInspectionEditParam, subInspection);
        subInspection.setUpdateTime(new Date());
        subInspectionMapper.update(subInspection);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void insert(SubInspectionEditParam subInspectionEditParam) {
        log.debug("开始处理【新增检查项】的请求，参数：{}", subInspectionEditParam);
        SubInspection subInspection = new SubInspection();
        BeanUtils.copyProperties(subInspectionEditParam, subInspection);
        subInspection.setCreateTime(new Date());
        subInspection.setStatus("10");
        if(subInspectionEditParam.getInsuranceCode() != null &&
                !subInspectionEditParam.getInsuranceCode().trim().isEmpty()){
            //自己编的固定算法，实际上调医保局接口
            double insurancePrice =subInspectionEditParam.getPrice()*0.7;
            subInspection.setInsurancePrice((int)insurancePrice);
        }else {
            subInspection.setInsurancePrice(subInspectionEditParam.getPrice());
        }
        Inspection inspection = new Inspection();
        inspection.setId(subInspection.getInspectionId());
        inspection.setPrice(subInspection.getPrice());
        inspection.setInsurancePrice(subInspection.getInsurancePrice());
        inspection.setUpdateTime(new Date());
        inspectionMapper.updateById(inspection);
        subInspectionMapper.insert(subInspection);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void delete(SubInspectionDeleteParam subInspectionDeleteParam) {
        log.debug("开始处理【删除检查项】的请求，参数：{}", subInspectionDeleteParam);
        subInspectionMapper.delete(subInspectionDeleteParam);
        Inspection inspection = new Inspection();
        inspection.setId(subInspectionDeleteParam.getInspectionId());
        inspection.setPrice(-subInspectionDeleteParam.getPrice());
        inspection.setInsurancePrice(-subInspectionDeleteParam.getInsurancePrice());
        log.debug("删除时修改价格{},{}",-subInspectionDeleteParam.getPrice(),-subInspectionDeleteParam.getInsurancePrice());
        inspection.setUpdateTime(new Date());
        inspectionMapper.updateById(inspection);

    }

    @Override
    public SubInspectionVO selectOneById(Long inspectionItemId, Long inspectionId) {
        log.debug("开始处理【根据检查项id和检查单id查询检查项】的请求，参数：{},{}", inspectionItemId,inspectionId);
        return subInspectionMapper.selectOneById(inspectionItemId,inspectionId);
    }

    @Override
    public List<UnInspectedItemVO> selectUnInspectedItem(UnInspectedItemQuery unInspectedItemQuery) {
        //先获得带有人员信息的检查单列表
        List<InspectionPersonVO> inspectionPersonVOList = getInspectionByPerson(unInspectedItemQuery);
        //准备一个结果集合用于合并所有检查项集合
        List<UnInspectedItemVO> unInspectedItemVOList = new ArrayList<>();
        //mapper层到时候要用code查询
        String code = unInspectedItemQuery.getCode();
        //遍历检查单集合，根据每一个检查单获取检查项集合，放到结果结合中
        if(inspectionPersonVOList != null && !inspectionPersonVOList.isEmpty()){
            inspectionPersonVOList.forEach(inspectionPersonVO -> {
                //查询检查项集合
                List<UnInspectedItemVO> unInspectedItemVOSubList =
                        subInspectionMapper.selectUnInspectedItem(inspectionPersonVO.getInspectionId(), code);
                if(unInspectedItemVOSubList != null && !unInspectedItemVOSubList.isEmpty()){
                    //合并集合前先把person信息传到集合中每个检查项上
                    List<UnInspectedItemVO> unInspectedItemVOSubResultList = unInspectedItemVOSubList
                            .stream()
                            .peek(unInspectedItemVO -> BeanUtils.copyProperties(inspectionPersonVO, unInspectedItemVO))
                            .collect(Collectors.toList());
                    //合并集合
                    unInspectedItemVOList.addAll(unInspectedItemVOSubResultList);
                }
            });
        }
        return unInspectedItemVOList;
    }

    private List<InspectionPersonVO> getInspectionByPerson(UnInspectedItemQuery unInspectedItemQuery) {
        OrderQuery orderQuery = new OrderQuery();
        BeanUtils.copyProperties(unInspectedItemQuery,orderQuery);
        //根据姓名和身份证号以及状态查询检查单
        List<OrderVO> inspectionOrderVOList
                = orderMapper.findInspectionsByPatientAndStatus(orderQuery);
        List<InspectionPersonVO> inspectionPersonVOList = null;
        if (inspectionOrderVOList != null && !inspectionOrderVOList.isEmpty()) {
            inspectionPersonVOList = inspectionOrderVOList
                    .stream()
                    //过滤掉未支付的订单
                    .filter(orderVO -> !InspectionStatus.NOT_PAYED.equals(orderVO.getStatus()))
                    //将OrderVO转换为InspectionPersonVO
                    .map(this::getInspectionPersonVO)
                    .collect(Collectors.toList());
        }
        return inspectionPersonVOList;
    }

    //将OrderVO转换为InspectionPersonVO
    private InspectionPersonVO getInspectionPersonVO(OrderVO orderVO) {
        InspectionPersonVO inspectionPersonVO = new InspectionPersonVO();
        BeanUtils.copyProperties(orderVO, inspectionPersonVO);
        inspectionPersonVO.setInspectionId(orderVO.getId());
        inspectionPersonVO.setPatientName(orderVO.getName());
        //查询医生姓名
        String doctorName = orderMapper.findDoctorNameById(orderVO.getDoctorId());
        inspectionPersonVO.setDoctorName(doctorName);
        return inspectionPersonVO;
    }
}
